package com.zhanghe.study.suanfa;

/**
 * 求质数之和
 *
 * @author: zhanghe
 * @date: 2020/5/31 23:56
 */
public class Main6 {
    public static void main(String[] args) {
        System.out.println("sum为" + sum(100));
        System.out.println("sum为" + sum1(100));
    }

    /**
     * 普通方法
     *
     * @param n
     * @return
     */
    public static int sum1(int n) {
        int sum = 0;
        int count = 0;
        boolean issushu;
        if (n <= 2) {
            return 0;
        } else {
            for (int i = 3; i <= n; i++) {
                issushu = true;
                for (int j = 2; j < i; j++) {
                    count++;
                    if (i % j == 0) {
                        issushu = false;
                        break;
                    }
                }
                if (issushu) {
                    System.out.printf("%d\t", i);
                    sum += i;
                }
            }
        }
        System.out.println();
        System.out.println("一共执行" + count + "次");
        return sum;
    }

    /**
     * 优化方法
     *
     * @param n
     * @return
     */
    public static int sum(int n) {
        int sum = 0;
        int count = 0;
        boolean issushu;
        if (n <= 2) {
            return 0;
        } else {
            for (int i = 3; i <= n; i += 2) {
                issushu = true;
                for (int j = 2; j <= Math.sqrt(i); j++) {
                    count++;
                    if (i % j == 0) {
                        issushu = false;
                        break;
                    }
                }
                if (issushu) {
                    System.out.printf("%d\t", i);
                    sum += i;
                }
            }
        }
        System.out.println();
        System.out.println("一共执行" + count + "次");
        return sum;
    }
}
